<template>
    <div>
        <!-- Navigation Bar -->
        <div class="nav-bar">
            <h1>User Profile</h1>
            <div class="nav-buttons">
                <el-button type="primary" @click="editMode = !editMode">
                    {{ editMode ? 'Cancel Edit' : 'Edit Information' }}
                </el-button>
                <el-button @click="ToOrder">To My Orders</el-button>
                <el-button @click="router.push('/myrecord')">To My Logs</el-button>
                <el-button type="danger"  @click="handleloginOut">Login Out</el-button>
            </div>
        </div>

        <div class="cards-container">
            <div class="cards-left">
                <!-- User Information Card -->
                <el-card class="profile-card">
                    <template #header>
                        <div class="card-header">
                            <h2>User Information</h2>
                        </div>
                    </template>
                    <el-form :model="userInfo" label-width="120px" :disabled="!editMode">
                        <el-form-item label="User Name">
                            <el-input v-model="userInfo.account.username" disabled></el-input>
                        </el-form-item>
                        <div class="form-row">
                            <el-form-item label="First Name">
                                <el-input v-model="userInfo.account.firstname" placeholder="First Name"></el-input>
                            </el-form-item>
                            <el-form-item label="Last Name">
                                <el-input v-model="userInfo.account.lastname" placeholder="Last Name"></el-input>
                            </el-form-item>
                        </div>
                        <div class="form-row">
                            <el-form-item label="Email">
                                <el-input v-model="userInfo.account.email"></el-input>
                            </el-form-item>
                            <el-form-item label="Phone">
                                <el-input v-model="userInfo.account.phone"></el-input>
                            </el-form-item>
                        </div>
                    </el-form>
                </el-card>
                <!-- Profile Preferences Card -->
                <el-card class="profile-card">
                    <template #header>
                        <div class="card-header">
                            <h2>Profile Preferences</h2>
                        </div>
                    </template>
                    <el-form :model="userInfo" label-width="120px" :disabled="!editMode">
                        <el-form-item label="Language">
                            <el-select v-model="userInfo.profile.languagePreference" placeholder="Select language">
                                <el-option label="English" value="english" />
                                <el-option label="Japanese" value="japanese" />
                                <el-option label="Chinese" value="chinese" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Category">
                            <el-select v-model="userInfo.profile.favoriteCategory" placeholder="Select category">
                                <el-option label="FISH" value="FISH" />
                                <el-option label="DOGS" value="DOGS" />
                                <el-option label="REPTILES" value="REPTILES" />
                                <el-option label="CATS" value="CATS" />
                                <el-option label="BIRDS" value="BIRDS" />
                            </el-select>
                        </el-form-item>
                        <div class="form-row">
                            <el-form-item label="Enable MyList">
                                <el-switch v-model="userInfo.profile.myListOption" />
                            </el-form-item>
                            <el-form-item label="Enable Banner">
                                <el-switch v-model="userInfo.profile.bannerOption" />
                            </el-form-item>
                        </div>
                    </el-form>
                </el-card>
            </div>
            <!-- Address Information Card -->
            <el-card class="profile-card">
                <template #header>
                    <div class="card-header">
                        <h2>Address Information</h2>
                    </div>
                </template>
                <el-form :model="userInfo" label-width="120px" :disabled="!editMode" class="address-form">
                    <el-form-item label="Address 1">
                        <el-input v-model="userInfo.account.address1"></el-input>
                    </el-form-item>
                    <el-form-item label="Address 2">
                        <el-input v-model="userInfo.account.address2"></el-input>
                    </el-form-item>
                    <el-form-item label="City">
                        <el-input v-model="userInfo.account.city"></el-input>
                    </el-form-item>
                    <el-form-item label="State">
                        <el-input v-model="userInfo.account.state"></el-input>
                    </el-form-item>
                    <el-form-item label="Zip">
                        <el-input v-model="userInfo.account.zip"></el-input>
                    </el-form-item>
                    <el-form-item label="Country">
                        <el-input v-model="userInfo.account.country"></el-input>
                    </el-form-item>
                </el-form>
            </el-card>


        </div>

        <!-- Save Button -->
        <div class="action-buttons" v-if="editMode">
            <el-button type="primary" @click="saveUserInfo">Save Changes</el-button>
            <el-button @click="editMode = false">Cancel</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import apiClient from '@/api/api'
import { useRouter } from 'vue-router'
import store from '@/store'
// 编辑模式状态
const editMode = ref(false)
// 路由
const router = useRouter()
// 用户信息接口
interface UserInfo {
    sign: {
        username: string
    },
    profile: {
        username: string,
        favoriteCategory: string,
        myListOption: boolean,
        bannerOption: boolean,
        languagePreference: string
    },
    account: {
        username: string,
        email: string,
        firstname: string,
        lastname: string,
        status: string,
        address1: string,
        address2: string,
        city: string,
        state: string,
        zip: string,
        country: string,
        phone: string
    },
    bannerData: {
        favouriteCategory: string,
        bannerName: string
    }
}

// 用户信息数据
const userInfo = reactive<UserInfo>({
    sign: {
        username: ''
    },
    profile: {
        username: '',
        favoriteCategory: '',
        myListOption: false,
        bannerOption: false,
        languagePreference: ''
    },
    account: {
        username: '',
        email: '',
        firstname: '',
        lastname: '',
        status: '',
        address1: '',
        address2: '',
        city: '',
        state: '',
        zip: '',
        country: '',
        phone: ''
    },
    bannerData: {
        favouriteCategory: '',
        bannerName: ''
    }
})

// 获取用户信息
const fetchUserInfo = async () => {
    if (!localStorage.getItem('token')) {
        ElMessage.warning('Please login first')
        router.push('/login')
        return
    }
    try {
        // Get user information
        const response = await apiClient.get('/users')
        if (response.data.status === 0) {
            const data = response.data.data
            Object.assign(userInfo, data)
        }
    } catch (error) {
        console.error('Failed to get user information:', error)
        ElMessage.error('Failed to get user information')
    }
}
// 跳转到订单页面
const ToOrder = () => {
    window.location.href='/page2/myorders'
}
// 保存用户信息
const saveUserInfo = async () => {
    try {

        // 发送更新请求
        const response = await apiClient.put(`/users`, userInfo)
        if (response.data && response.data.status === 0) {
            ElMessage.success('Profile updated successfully')
            editMode.value = false
        } else {
            ElMessage.error(response.data?.message || 'Update failed')
        }
    } catch (error) {
        console.error('Failed to update user information:', error)
        ElMessage.error('Failed to update user information')
    }
}
// 退出登录
const handleloginOut = () => {
    localStorage.removeItem('token')
    store.commit('setLoginStatus', false)
    ElMessage.success('Logout successfully')  
    router.push('/login')
}
// 组件挂载时获取用户信息
onMounted(() => {
    fetchUserInfo()
})
</script>

<style scoped>
.nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
}

.nav-buttons {
    display: flex;
    gap: 10px;
}

.cards-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.cards-left {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.profile-card {
    width: auto;
    padding: 20px;
    border-radius: 8px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.action-buttons {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
}

h1 {
    margin: 0;
    color: #409EFF;
    font-size: 28px;
}

h2 {
    margin: 0;
    font-size: 20px;
    color: #303133;
    font-weight: 600;
}

.el-form-item {
    margin-bottom: 25px;
}

.el-form-item__content {
    min-height: 40px;
}

.el-input,
.el-select {
    width: 100%;
}

.el-form {
    padding: 0 20px;
}

.address-form .el-form-item {
    /* 增加表单项之间的间距 */
    margin-bottom: 35px;

}

@media (max-width: 1200px) {
    .cards-container {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .cards-container {
        grid-template-columns: 1fr;
    }

    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
}
</style>